package com.ysg.utils;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.Activity;
import android.content.Context;
import android.os.IBinder;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class YKeyboardUtils {


    /**
     * 显示软键盘
     */
    public static void show(Context context) {
        InputMethodManager inputmethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        if (inputmethodManager != null && inputmethodManager.isActive()) {
            inputmethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 显示软键盘
     */
    public static void show(View view) {
        if (view == null) {
            return;
        }
        if (view instanceof EditText) {
            view.requestFocus();
        }
        InputMethodManager inputmethodManager = (InputMethodManager) view.getContext().getSystemService(INPUT_METHOD_SERVICE);
        if (inputmethodManager != null) {
            inputmethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    /**
     * 隐藏软键盘
     */
    public static void hide(View view) {
        try {
            InputMethodManager inputmethodManager = (InputMethodManager) view.getContext().getSystemService(INPUT_METHOD_SERVICE);
            if (inputmethodManager != null) {
                inputmethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 强制隐藏软键盘
     */
    public static void hide(Activity activity) {
        InputMethodManager inputmethodManager = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
        if (inputmethodManager != null && inputmethodManager.isActive()) {
            IBinder binder = activity.getWindow().getDecorView().getWindowToken();
            inputmethodManager.hideSoftInputFromWindow(binder, 0);
        }
    }

    /**
     * 强制隐藏软键盘
     */
    public static void hide(Context context) {
        if (context instanceof Activity) {
            hide(((Activity)context));
        }
    }

}
